package yagl.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import net.sf.json.JSONArray;
import yagl.agent.YaglAgent;
import common.ChanageDocToPdf;
import common.MyUtils;
import common.BaseClasses.CommonAction;
import common.BaseClasses.util.IocUtil;

public class YaglAction extends CommonAction{
	private YaglAgent yaglAgent;
	private Map<Object, Object> resultMap;
    public Map<Object, Object> getResultMap() {
		return resultMap;
	}
	public void setResultMap(Map<Object, Object> resultMap) {
		this.resultMap = resultMap;
	}
	public YaglAction(){
    	try {
			this.yaglAgent=(YaglAgent) IocUtil.getIocImpl("yagl/ioc/ioc-ya.xml", "yaglAgent");
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    //保存一个预案
    public String saveYa(){
    	Map map=modelDriverMapInd(request);
    	map.put("id", MyUtils.getUUID());
    	yaglAgent.saveYa(map);
    	return "success";
    }
    //根据预案的时间和名字查询预案
    public String searchYa(){
    	Map map=modelDriverMapInd(request);
    	paramMap.put("yaName", getParameter("yaName"));
    	paramMap.put("startTime", getParameter("startTime"));
    	paramMap.put("endTime", getParameter("endTime"));
    	System.out.println("=========="+getIntParameter("pageSize"));
    	resultMap=yaglAgent.findYaByPage(1, getIntParameter("pageSize"), map);
    	System.out.println("分页查询结果---------"+resultMap);
    	setPageParam(resultMap);
    	return "toYaglFenyePage";
    }
    public String selectAllYa(){
    	Map map=new HashMap();
    	resultMap=yaglAgent.findYaByPage(1,getIntParameter("pageSize"),map);
    	System.out.println("查询结果-------------"+resultMap);
    	setPageParam(resultMap);
    	return "toYaglPage";
    }
    public String findYaByPage(){
    	paramMap.put("yaName", getParameter("yaName",""));
    	paramMap.put("startTime",getParameter("startTime",""));
    	paramMap.put("endTime", getParameter("endTime",""));
    	Map map=new HashMap();
    	map.put("yaName", getParameter("yaName", ""));
    	map.put("startTime", getParameter("startTime", ""));
    	map.put("endTime", getParameter("endTime",""));
    	resultMap=yaglAgent.findYaByPage(pageBean.getCurrentPage(), pageBean.getPageSize(), map);
    	setPageParam(resultMap);
    	return "toYaglFenyePage";
    }
    /**
     * 根据id查询一个预案
     */
    public void findYaById(){
    	Map map=modelDriverMapInd(request);
    	List list=yaglAgent.selectYaById(map);
    	writeStringToResponse(JSONArray.fromObject(list));
    }
    /**
     * 更新一个预案
     */
    public String updateYa(){
    	Map map=new HashMap();
    	map.put("id", getParameter("id"));
        String newFilePath=getParameter("pl_filepath");
        List list=yaglAgent.selectYaById(map);
        Map<String, Object> dataMap=(Map<String, Object>) list.get(0);
        String oldFilePath=(String) dataMap.get("pl_filepath");
        //如果更新时文件路径跟数据库中的文件路径不同则删除服务器端的旧文件
        if(!newFilePath.equals(oldFilePath)){
        	String baseUrl=request.getSession().getServletContext().getRealPath("/");
        	String filepath=baseUrl+oldFilePath;
        	File file=new File(filepath);
        	 //得到源文件名字
       	    String fileName=file.getName();
       	     //得到文件类型
       	    String fileType=fileName.substring((fileName.length() - 4),fileName.length());
       	    deleteFileByType(baseUrl,fileType,oldFilePath,file);
        }
        map.put("pl_nm", getParameter("pl_nm"));
        map.put("pl_dt", getParameter("pl_dt"));
        map.put("pl_type", getParameter("pl_type"));
        map.put("pl_filepath", getParameter("pl_filepath"));
        map.put("file_type", getParameter("file_type"));
        map.put("file_name", getParameter("file_name"));
        System.out.println(map);
        yaglAgent.updateYa(map);
    	return "success";
    }
    /**
     * 批量下载文件
     */
    public void piLiangXiaZai(){
    	SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String[] filePathArray=request.getParameter("filepaths").split(";");
		String[] fileNameArray=null;
		try {
			fileNameArray = new String(request.getParameter("filenames").trim().getBytes("ISO8859-1"), "utf-8").split(";");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String[] fileTypeArray=request.getParameter("filetypes").split(";");
		//过滤掉下载文件时服务器端的两个相同文件
		ArrayList<String> nameTypeList=new ArrayList<String>();
		Map<String,String> map=new HashMap<String, String>();
		for(int i=0;i<fileNameArray.length;i++){
			if(!nameTypeList.contains(fileNameArray[i]+"."+fileTypeArray[i])){
				nameTypeList.add(fileNameArray[i]+"."+fileTypeArray[i]);
				map.put(fileNameArray[i]+"."+fileTypeArray[i], filePathArray[i]);
			}
		}
		System.out.println(map);
		//产生的压缩文件路径和名字
		String filepath=request.getSession().getServletContext().getRealPath("/uploadfile/temp")+"\\"+format.format(new Date())+".zip";
		File f=null;
		File tempFile=null;
		if(fileNameArray!=null&&filePathArray!=null&&fileNameArray.length>0&&fileNameArray.length==filePathArray.length){
			try {
				tempFile=new File(filepath);
				f=new File(filepath);
				MyUtils.createFile(f);
				ZipOutputStream out=new ZipOutputStream(new FileOutputStream(f));
				out.putNextEntry(new ZipEntry("/"));
				Set set=map.entrySet();
				Iterator it=set.iterator();
				while(it.hasNext()){
					Entry<String, String> entry=(Entry<String, String>) it.next();
					FileInputStream In=new FileInputStream(request.getSession().getServletContext().getRealPath("/")+entry.getValue());
					//开始写入新的ZIP条目并将流定位到条目数据的开始处
					out.putNextEntry(new ZipEntry(new String(entry.getKey())));
					int b;
					while((b=In.read())!=-1){
						out.write(b);
					}
					In.close();
				}
				out.flush();
				out.close();
				//以流的形式下载文件,获得目标文件下载的输入流
				InputStream fis=new BufferedInputStream(new FileInputStream(filepath));
				byte[] buffer=new byte[fis.available()];
				fis.read(buffer);
				fis.close();
				response.reset();
				response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("批量打包下载"+".zip","UTF-8"));
				response.addHeader("Content-Length", "" + tempFile.length());
				OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
				response.setContentType("application/octet-stream");//设置响应的MIME类型
				toClient.write(buffer);//你写的是buffer，也就是fis，也就是filepath这里对应的zip文件。这个是uuid.zip的话，上面的filename可以是abcd.zip
				toClient.flush();
				toClient.close();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}finally{
				if(tempFile.exists()){
					tempFile.delete();
					if(tempFile.exists()){
						System.out.println("------删除临时文件失败-----");
					}else{
						System.out.println("------成功删除临时打包文件----");
					}
				}
			}
		}else{
			System.out.println("请求下载文件的路径或者文件名出现问题");
		}
    }
   
	//批量删除预案管理
    public void batchDeleteYa(){
         String idArr=getParameter("idArr");
         String pathArr=getParameter("pathArr");
         deleteFileFromServer(pathArr);
         String result=yaglAgent.batchDeleteYa(idArr);
         writeStringToResponse(result);
    }
    //删除预案管理中的附件
    private void deleteFileFromServer(String pathArr) {
          String pathArray[]=pathArr.split(";");
          //获取请求地址
          String baseUrl=request.getSession().getServletContext().getRealPath("/");
          for(int i=0;i<pathArray.length;i++){
        	 String sourceFilePath=baseUrl+pathArray[i];
        	 //得到源文件
        	 File file=new File(sourceFilePath);
        	 //得到源文件名字
        	 String fileName=file.getName();
        	 //得到文件类型
        	 String fileType=fileName.substring((fileName.length() - 4),fileName.length());
        	 deleteFileByType(baseUrl,fileType,pathArray[i],file);
          }
	}
	private void deleteFileByType(String baseUrl,String fileType, String sourceFilePath, File file) {
		 if(fileType.equals("docx")){
    		 //如果是word文档，则删除word文档的同时，如果该文档被查看过，还得删除查看时生成的pdf文档
    		 String pdfFilePath=baseUrl+sourceFilePath.replace("docx","pdf");
    		 File pdfFile=new File(pdfFilePath);
    		 deleteFile(pdfFile);
    		 deleteFile(file);
    	 }else if(fileType.equals(".doc")){
    		 String pdfFilePath=baseUrl+sourceFilePath.replace("doc", "pdf");
    		 File pdfFile=new File(pdfFilePath);
    		 deleteFile(pdfFile);
    		 deleteFile(file);
    	 }else if(fileType.equals(".rar")){
    		 deleteFile(file);
    	 }else if(fileType.equals(".zip")){
    		 deleteFile(file);
    	 }else if(fileType.equals(".txt")){
    		 deleteFile(file);
    	 }else if(fileType.equals(".pdf")){
    		 deleteFile(file);
    	 }
	}
	private void deleteFile(File file) {
		 if(file.isFile()&&file.exists()){
			 file.delete();
			 System.out.println("文件删除成功");
		 }
	}
	//查看word格式的文件时把word格式的文件转换为pdf格式
    public void changeWordToPdf(){
    	//得到数据库中文件保存的相对路径
    	String filepath=request.getParameter("filepath");
    	//获取请求地址
    	String baseUrl=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
    	//得到源文件路径
    	String sourceFilePath=baseUrl+request.getParameter("filepath");
    	//得到源文件
    	File file=new File(sourceFilePath);
    	//得到源文件的名字
    	String fileName=file.getName();
    	//得到文件类型
    	String fileType=fileName.substring((fileName.length() - 4),fileName.length());
    	if(fileType.equals("docx")){
    	    String s=getReturnPath(sourceFilePath,filepath,fileName,5);
    		writeStringToResponse(s);
    	}else if(fileType.equals(".doc")){
    		String s=getReturnPath(sourceFilePath,filepath,fileName,4);
    		writeStringToResponse(s);
    	}
    }
	private String getReturnPath(String sourceFilePath,String filepath, String fileName, int i) {
		//得到路径中除去文件名字后的文件夹路径
		String newFilePath=filepath.substring(0,filepath.length()-fileName.length()-1);
    	String tempDir=request.getSession().getServletContext().getRealPath(newFilePath);
    	//从文件的名字中获取到除掉文件后缀名的路径，如文件名为a.docx,则获取a
    	String fileNameNoType=fileName.substring(0, (fileName.length() - i));
    	File file1=new File(tempDir+"\\"+fileNameNoType+".pdf");
    	//判断服务器端是否已经有了该docx文档转换成的pdf文档,如果有返回该文档的路径，如果没有进行转换
    	if(file1.exists()){
    		return newFilePath+"\\"+fileNameNoType+".pdf";
    	}else{
    		File tFile=new File(tempDir);
    		if(!tFile.exists())
    			tFile.mkdir();
    		String result=ChanageDocToPdf.chanage(sourceFilePath,tempDir,17);
    		return result.substring(result.indexOf("uploads"), result.length());
    	}
	}
	public YaglAgent getYaglAgent() {
		return yaglAgent;
	}
	public void setYaglAgent(YaglAgent yaglAgent) {
		this.yaglAgent = yaglAgent;
	}
}
